package com.youzhi.backend.config;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Component("sessionDAO")
public class RedisSessionDao extends EnterpriseCacheSessionDAO {


    public static String session_prefix = "session:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        String sessionKey = getSessionKey(sessionId);
        BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(sessionKey);
        ops.set(session);
        ops.expire(session.getTimeout(), TimeUnit.MILLISECONDS);
        return sessionId;
    }

    @Override
    protected void cache(Session session, Serializable sessionId) {
        //重写cache方法，让session不缓存于内存,目的是为了自己控制session状态
    }


    @Override
    protected Session doReadSession(Serializable sessionId) {
        String sessionKey = getSessionKey(sessionId);
        return (Session) redisTemplate.opsForValue().get(sessionKey);
    }

    @Override
    protected void doUpdate(Session session) {
        String sessionKey = getSessionKey(session.getId());
        BoundValueOperations<String, Object> ops = redisTemplate.boundValueOps(sessionKey);
        ops.set(session);
        ops.expire(session.getTimeout(), TimeUnit.MILLISECONDS);
    }

    @Override
    protected void doDelete(Session session) {
        String sessionKey = getSessionKey(session.getId());
        redisTemplate.delete(sessionKey);
    }


    private String getSessionKey(Serializable sessionId) {
        return session_prefix + sessionId;
    }

}
